import { _decorator, Component, Node, Sprite, SpriteFrame, tween, v3, Vec3 } from 'cc';
import { EasingType } from '../../Scripts/Framework/Utils/TweenUtil';
const { ccclass, property } = _decorator;

@ccclass('WorldCar')
export class WorldCar extends Component {

    @property
    speed = 0;

    @property([Node])
    points: Node[] = [];

    @property([SpriteFrame])
    carSfs: SpriteFrame[] = [];

    index = 0;

    sprite: Sprite;

    start() {
        this.sprite = this.getComponent(Sprite);
        this.Move();
    }

    update(deltaTime: number) {

    }

    Move() {
        if (this.index < this.points.length - 1) this.index++;
        else this.index = 0;
        let target = this.points[this.index];
        let dis = Vec3.distance(this.node.getWorldPosition(), target.getWorldPosition());
        let dir = v3();
        Vec3.subtract(dir, target.getWorldPosition(), this.node.getWorldPosition());
        if (Math.abs(dir.x) > Math.abs(dir.y)) {
            if (dir.x > 0) this.node.setScale(v3(1, 1, 1));
            else this.node.setScale(v3(-1, 1, 1));
            this.sprite.spriteFrame = this.carSfs[0];
        }
        else {
            if (dir.y > 0) this.sprite.spriteFrame = this.carSfs[2];
            else this.sprite.spriteFrame = this.carSfs[1];
            this.node.setScale(v3(1, 1, 1));
        }
        let time = dis / this.speed;
        tween(this.node)
            .to(time, { worldPosition: target.getWorldPosition() }, { easing: EasingType.quadInOut })
            .call(() => {
                this.node.setParent(target, true);
                this.Move();
            })
            .start();
    }
}


